package com.hspedu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.hspedu.springcloud.entity.Member;
import com.hspedu.springcloud.entity.Result;

import com.hspedu.springcloud.handler.CustomGlobalBlockHandler;
import com.hspedu.springcloud.handler.CustomGlobalFallbackHandler;
import com.hspedu.springcloud.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@Slf4j
public class MemberController {
    @Resource
    private MemberService memberService;
    private static int num = 0;

    @PostMapping(value = "/member/save")
    public Result save(@RequestBody Member member) {
        int result = memberService.save(member);
        log.info("reset= " + result);
        if (result > 0) { //成功
            return Result.success("添加用户成功member-service-nacos-provider-10004", result);
        } else {
            return Result.error("401", "添加用户失败");
        }
    }

    @GetMapping(value = "/member/get/{id}")
    public Result getMemberById(@PathVariable("id") Long id) {
        Member member = memberService.queryMemberById(id);
        log.info("查询结果= " + member);
        if (member != null) {
            return Result.success("查询成功 member-service-nacos-provider-10004", member);
        } else {
            return Result.error("402", "ID= " + id + " 不存在");
        }
    }

    @GetMapping("/news")
    @SentinelResource(value = "news",blockHandler = "newsBlockHandler")
    public Result queryNews(@RequestParam(value = "id",required = false) String id, @RequestParam(value = "type",required = false) String type)
    {
        log.info("到 DB 查询数据库.... ");
        return Result.success("返回 id= " + id + " 新闻 fromDB");
    }

    //热点 key 限制异常处理方法
    public Result newsBlockHandler(String id, String type, BlockException exception){
        return Result.success("查询 id= " + id+ " 新闻 触发热点 key 限制保护.. sorry");
    }

    @GetMapping(value = "/t6")
    @SentinelResource(
            value = "t6", blockHandlerClass = CustomGlobalBlockHandler.class, blockHandler = "handlerMethod1",
            fallbackClass = CustomGlobalFallbackHandler.class, fallback = "fallBackHandlerMethod1")
    public Result t6() {
        if (++num % 5 == 0) {//假定: 当访问 t6 资源次数是 5 的倍数时，就出现了一个 java 的异常
            throw new RuntimeException("num 的值异常 num= " + num);
        }
        log.info("执行 t6() 线程 id= " + Thread.currentThread().getId());
        return Result.success("200", "t6()执行成功");
    }

}
